﻿using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore.Sqlite;
using Microsoft.EntityFrameworkCore.SqlServer;
using Pomelo.EntityFrameworkCore.MySql;

namespace CKY.AgentPlatform.EntityFrameworkCore;

/* This class is needed for EF Core console commands
 * (like Add-Migration and Update-Database commands) */
public class AgentPlatformDbContextFactory : IDesignTimeDbContextFactory<AgentPlatformDbContext>
{
    public AgentPlatformDbContext CreateDbContext(string[] args)
    {
        AgentPlatformEfCoreEntityExtensionMappings.Configure();

        var configuration = BuildConfiguration();
        var connectionString = configuration.GetConnectionString("Default");

        var builder = new DbContextOptionsBuilder<AgentPlatformDbContext>();

        // 根据连接字符串自动选择数据库提供程序
        if (connectionString.Contains("Data Source=") && connectionString.EndsWith(".db"))
        {
            builder.UseSqlite(connectionString);
        }
        else if (connectionString.Contains("Server=") || connectionString.Contains("Data Source="))
        {
            builder.UseSqlServer(connectionString);
        }
        else if (connectionString.Contains("Host="))
        {
            builder.UseNpgsql(connectionString);
        }
        else if (connectionString.Contains("Server=") && connectionString.Contains("User="))
        {
            builder.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 0)));
        }
        else
        {
            // 默认使用 SQLite
            builder.UseSqlite(connectionString);
        }

        return new AgentPlatformDbContext(builder.Options);
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../CKY.AgentPlatform.DbMigrator/"))
            .AddJsonFile("appsettings.json", optional: false);

        return builder.Build();
    }
}
